package com.jp.knowledge.view;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.util.JsonUtil;
import com.jp.knowledge.util.L;
import com.jp.knowledge.webUtil.X5WebView;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.tencent.smtt.utils.TbsLog;

/**
 * Created by jiayen on 16/11/23.
 */

public class CustomerWebView {

    private Context mContext;



    //雷达
    public static final String follow="follow";//雷达
    public static final String headlines="headlines";//头条
    public static final String experience="experience";//体验
    public static final String discover="discover";//发现
    public static final String mine="mine";//发现我的

    private boolean loadError=false;

    private X5WebView contView;
    private String url = "http://192.168.31.113:3001/";// "http://192.168.32.65:8080/test/test.html";
    //	private String url = "http://debugm.jp580.com/";// "http://192.168.32.65:8080/test/test.html";
    // //
    private String curUrl;

    private String curlPath;
    private TextView startPage;// 启动页

    public String[] web_module_name = new String[]{"headlines", "follow", "experience", "discover", "mine"};// 头条、关注、轻体验、发现、我的  headlines   follow  compete  discover mine  竞爆compete

    public  CustomerWebView(Context mContext){
        this.mContext=mContext;
        initView();
    }

    /**
     * 初始view
     */
    private void initView() {

//        QbSdk.allowThirdPartyAppDownload(true);
        contView = initWebView();//(X5WebView) findViewById(R.id.content);
        contView.getSettings().setUserAgentString("app_jp;jp580.com");
        contView.loadUrl(url);
    }


    public    void setCurrentPath(String path){
        this.curlPath = path;
        contView.loadUrl("javascript:windowNativeBridge.setInWebView(2)");
        L.e("setCurrentPath",path);
        if(contView!=null) {
            contView.setVisibility(View.GONE);
            JsonObject obj = new JsonObject();
            obj.addProperty("type","show_web");

            contView.loadUrl("javascript:windowNativeBridge.setCurrentPath('" + path + "'),Android.jsCallback('"+obj.toString()+"')");//设置当前页面路径
        }
    }


    /**
     * 添加到容器中
     * @param parentView
     */
    public void setParentView(FrameLayout parentView){
        parentView.addView(contView, new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.FILL_PARENT,
                FrameLayout.LayoutParams.FILL_PARENT));
    }
    /**
     * 设置用户信息到h5里面
     * @param userData
     */
    public void setUserData(UserData userData){
        contView.loadUrl("javascript:windowNativeBridge.setUserInfoData('"+userData==null?"{}":JsonUtil.getInstance().objToJson(userData)+"')");
    }
    private X5WebView initWebView(){
        Log.e("0819", " before is " + System.currentTimeMillis());
        final X5WebView mWebView = new X5WebView(mContext);
        Log.e("0819", " after is " + System.currentTimeMillis());


        Log.w("grass", "Current SDK_INT:" + Build.VERSION.SDK_INT);
//

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view,
                                                              WebResourceRequest request) {
                // TODO Auto-generated method stub

                Log.e("should", "request.getUrl().toString() is " + request.getUrl().toString());

                return super.shouldInterceptRequest(view, request);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                L.d("title: " + title);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO Auto-generated method stub

            }
        });

        mWebView.setDownloadListener(new DownloadListener() {

            @Override
            public void onDownloadStart(String arg0, String arg1, String arg2,
                                        String arg3, long arg4) {
                L.d("url: " + arg0);
                new AlertDialog.Builder(mContext)
                        .setTitle("你即将下载")
                        .setPositiveButton("yes",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        ToasUtil.toast(
                                                mContext,
                                                "fake message: i'll download...");
                                    }
                                })
                        .setNegativeButton("no",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        // TODO Auto-generated method stub
                                        ToasUtil.toast(
                                                mContext,
                                                "fake message: refuse download...");
                                    }
                                })
                        .setOnCancelListener(
                                new DialogInterface.OnCancelListener() {

                                    @Override
                                    public void onCancel(DialogInterface dialog) {
                                        // TODO Auto-generated method stub
                                        ToasUtil.toast(
                                                mContext,
                                                "fake message: refuse download...");
                                    }
                                }).show();
            }
        });


        WebSettings webSetting = mWebView.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(mContext.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(mContext.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(mContext.getDir("geolocation", 0)
                .getPath());
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        long time = System.currentTimeMillis();
        TbsLog.d("time-cost", "cost time: "
                + (System.currentTimeMillis() - time));
        CookieSyncManager.createInstance(mContext);
        CookieSyncManager.getInstance().sync();
        return  mWebView;
    }




}
